package other.system.client.oa;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.http.*;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.XoqlService;
import other.system.client.apitool.OAClientUtils;
import other.system.client.oa.submit.*;
import other.system.client.util.*;

import java.util.*;

/**
 * @Description: 6个模块提交审批数据到OA
 * @Author: 黎炎松
 * @Date: 2024/6/26 15:05
 */
@RestApi(baseUrl = "/xsy/oaApproval")
public class SubmitApprovalService {

    public static String cancelMes = "CRM手动撤回";

    private static final Logger logger = LoggerFactory.getLogger();

    public static void main(String[] args) throws Exception {
        SubmitApprovalService submitApprovalService = new SubmitApprovalService();

        //submitApprovalService.pushDeBookingToOA(3424723389291138L);
        submitApprovalService.undoApprovalData(7, 3618742085278275L);
    }

    /**
     * 推送报价单数据到OA审批 quote
     * @param
     * @return
     */
    @RestMapping(value = "/pushQuoteToOA", method = RequestMethod.POST)
    public String pushQuoteToOA(@RestQueryParam(name = "id") Long quoteId) {
        logger.info("推送报价单 quoteId = " + quoteId);
        SubmitQuote submitQuote = new SubmitQuote();
        return submitQuote.pushQuoteToOA(quoteId);
    }


    /**
     * 推送合同数据到OA审批 contract
     * @param
     * @return
     */
    @RestMapping(value = "/pushContractToOA", method = RequestMethod.POST)
    public String pushContractToOA(@RestQueryParam(name = "id") Long contractId) throws InterruptedException {
        logger.info("推送合同 contractId = " + contractId);
        Thread.sleep(2500);
        SubmitContract submitContract = new SubmitContract();
        return submitContract.pushContractToOA(contractId);
    }

    /**
     * 推送订单数据到OA审批 order
     * @param
     * @return
     */
    @RestMapping(value = "/pushOrderToOA", method = RequestMethod.POST)
    public String pushOrderToOA(@RestQueryParam(name = "id") Long orderId) throws InterruptedException {
        logger.info("推送订单 orderId = " + orderId);
        Thread.sleep(2500);
        SubmitContract submitContract = new SubmitContract();
        return submitContract.pushOrderToOA(orderId, 1);
    }

    /**
     * 推送deBooking数据到OA审批 order
     * @param
     * @return
     */
    @RestMapping(value = "/pushDeBookingToOA", method = RequestMethod.POST)
    public String pushDeBookingToOA(@RestQueryParam(name = "id") Long deBookingId) {
        logger.info("推送deBooking deBookingId = " + deBookingId);
        SubmitContract submitContract = new SubmitContract();
        return submitContract.pushOrderToOA(deBookingId, 2);
    }

    /**
     * 推送投标盖章类数据到OA审批  bidSeal__c
     * @param
     * @return
     */
    @RestMapping(value = "/pushBidToOA", method = RequestMethod.POST)
    public String pushBidToOA(@RestQueryParam(name = "id") Long bidId) {
        logger.info("推送投标盖章类 bidId = " + bidId);
        SubmitBid submitBid = new SubmitBid();
        return submitBid.pushBidToOA(bidId);
    }

    /**
     * 推送投标盖章类数据到OA审批  bidSeal__c
     * @param
     * @return
     */
    @RestMapping(value = "/pushBidToOA2", method = RequestMethod.POST)
    public String pushBidToOA2(@RestQueryParam(name = "id") Long bidId) {
        logger.info("推送投标盖章类 bidId = " + bidId);
        SubmitBid2 submitBid2 = new SubmitBid2();
        return submitBid2.pushBidToOA(bidId);
    }

    /**
     * 推送其他销售类数据到OA审批  customEntity39__c
     * @param
     * @return
     */
    @RestMapping(value = "/pushOtherSaleToOA", method = RequestMethod.POST)
    public String pushOtherSaleToOA(@RestQueryParam(name = "id") Long saleId) {
        logger.info("推送其他销售类 saleId = " + saleId);
        SubmitOtherSale submitOtherSale = new SubmitOtherSale();
        return submitOtherSale.pushOtherSaleToOA(saleId);
    }

    /**
     * 推送零星采购类数据到OA审批  sporadicProcurement__c
     * @param
     * @return
     */
    @RestMapping(value = "/pushSporadicPurchaseToOA", method = RequestMethod.POST)
    public String pushSporadicPurchaseToOA(@RestQueryParam(name = "id") Long sporadicPurchaseId) {
        logger.info("推送零星采购 sporadicPurchaseId = " + sporadicPurchaseId);
        SubmitSporadicPurchase submitSporadicPurchase = new SubmitSporadicPurchase();
        return submitSporadicPurchase.pushSporadicPurchaseToOA(sporadicPurchaseId);
    }

    /**
     * 推送市场活动类数据到OA审批  campaign
     * @param
     * @return
     */
    @RestMapping(value = "/pushCampaignToOA", method = RequestMethod.POST)
    public String pushCampaignToOA(@RestQueryParam(name = "id") Long campaignId) {
        logger.info("推送市场活动 campaignId = " + campaignId);
        SubmitCampaign submitCampaign = new SubmitCampaign();
        return submitCampaign.pushCampaignToOA(campaignId);
    }


    /**
     * 撤回OA的审批数据
     * @param moduleType  1.销售类盖章申请-报价单 2.销售类盖章申请-投标类文件  3.销售类盖章申请-其他销售类文件  4.销售合同评审 5.零星采购 6.市场活动 7.订单 8.deBooking
     * @param dataId
     * @return
     */
    @RestMapping(value = "/undoApprovalData", method = RequestMethod.POST)
    public String undoApprovalData(@RestQueryParam(name = "moduleType") int moduleType, @RestQueryParam(name = "dataId") Long dataId) {
        String LOGGER_MSG = "撤回OA的审批数据 ==> ";
        try {

            // 判断是那个模块
            String objKey = "quote";
            switch (moduleType) {
                case 1:
                    objKey = "quote";
                    break;
                case 2:
                    objKey = "bidSeal__c";
                    break;
                case 3:
                    objKey = "customEntity39__c";
                    break;
                case 4:
                    objKey = "contract";
                    break;
                case 5:
                    objKey = "sporadicProcurement__c";
                    break;
                case 6:
                    objKey = "campaign";
                    break;
                case 7:
                    objKey = "_order";
                    break;
                case 8:
                    objKey = "debooking__c";
                    break;
            }

            // 根据数据id查找对应的oa审批id
            String sql = String.format("select id,oaApprovalId__c,ownerId.LoginName__c ownerOaAccount,ownerId.personalEmail ownerOaEmail " +
                    " from %s where id = '%s' ", objKey, dataId);
            List<JSONObject> objectList = XoqlService.instance().query(sql, true).getRecords();
            logger.info(LOGGER_MSG + "objectList:" + objectList);
            if (objectList == null || objectList.size() <= 0 || objectList.get(0).getString("oaApprovalId__c") == null) {
                logger.info(LOGGER_MSG + "查询不到关联OA的数据ID: " + dataId);
                return TfReturnMsgTools.getFailResult("查询不到关联OA的数据ID: " + dataId);
            }

            // 拼接需要发送的数据
            JSONObject jsonObject = objectList.get(0);
            String oaApprovalId = jsonObject.getString("oaApprovalId__c");
            logger.info(LOGGER_MSG + "oaApprovalId: " + oaApprovalId);

            // 发送的数据
            JSONObject sendData = new JSONObject();
            sendData.put("fdId", oaApprovalId); // 文档id

            // 获取当前数据所有人的OA账号
            JSONObject oaObject = new JSONObject();
            oaObject.put("ownerOaAccount", jsonObject.getString("ownerOaAccount"));
            oaObject.put("ownerOaEmail", jsonObject.getString("ownerOaEmail"));
            JSONObject oaAccount = SubmitSuper.getOaAccount(oaObject, 2);
            sendData.put("docCreator", oaAccount);

            // 撤回需要的参数
            JSONObject operationData = new JSONObject();
            operationData.put("operationType", "drafter_return");
            operationData.put("auditNote", cancelMes);
            operationData.put("handler", oaAccount);
            sendData.put("flowParam", operationData);

            // 发送数据
            logger.info( "请求的数据 ==> ");
            logger.info(String.valueOf(sendData));

            ResultBody resultBody = OAClientUtils.sendPost(sendData, OAClientUtils.UNDO_APPROVAL_URL, false);
            logger.info(LOGGER_MSG + "resultBody: " + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.info(LOGGER_MSG + "撤回OA发送请求异常: " + resultBody.getMessage());
                return TfReturnMsgTools.getFailResult("撤回OA发送请求异常:" + resultBody.getMessage());
            }

            // 撤回后对当前数据进行解锁
            JSONObject updateData = new JSONObject();
            updateData.put("id", dataId);
            updateData.put("lockStatus", 1);
            updateData.put("oaApprovalStatus__c", 2);
            updateObjetData(updateData, objKey == "_order" ? "order" : objKey);

            return TfReturnMsgTools.getSuccessResult("撤销成功");
        } catch (Exception e) {
            return TfReturnMsgTools.getFailResult("撤回OA审批数据异常:" + e.getMessage());
        }
    }

    /**
     * 更新对象的数据
     * @param updateData
     * @param apiKey
     * @throws Exception
     */
    public void updateObjetData(JSONObject updateData,String apiKey) throws Exception {
        logger.info("apiKey：" + apiKey);
        logger.info("需要更新的数据：" + updateData.toString());
        JSONObject params = new JSONObject();
        params.put("data", updateData);
        Long id = updateData.getLong("id");
        RkhdHttpClient httpClient = new RkhdHttpClient();
        RkhdHttpData data  = RkhdHttpData.newBuilder()
                .callType("PATCH")
                .callString("/rest/data/v2.0/xobjects/"+apiKey+"/"+id)
                .header("xsy-criteria", "10")
                .body(params.toJSONString())
                .build();
        String execute = httpClient.execute(data, e -> e);
        JSONObject result = JSONObject.parseObject(execute);
        logger.info("更新结果：" + result);
        if(result.getInteger("code") != 200){
            throw new RuntimeException(result.getString("msg"));
        }
    }

}
